<template>
  <basic-dialog :visible="addEditDialog"
                minWidth="520px"
                :title="isEdit ? '修改点位': '添加点位'"
                isShowClose
                @submit="submit"
                @close="hideDialog"
                :isShowInnerLoading="loading">
    <div>
      <q-form ref="form" class="dialog-content" greedy>
        <div style="padding: 20px 20px 0px 20px">
          <div class="title">基本信息</div>
          <div class="flex">
            <yz-input v-model="form.repType"
                      inputType="select"
                      :rules="[0]"
                      :options="typeOptions"
                      title="上报类型"
            />
            <q-select
              style="padding-bottom: 20px;margin-left: 20px;width: 180px"
              v-model="form.serviceTypeId"
              :options="nameOptionData"
              :disable="form.repType === '4'"
              dense
              options-dense
              emit-value
              map-options
              outlined
            >
            </q-select>
          </div>

          <div class="flex" v-if="form.repType === '2' && form.serviceTypeId === 'A'">
            <yz-input v-model="form.partcountType"
                      inputType="select"
                      :rules="[0]"
                      :options="partcountType"
                      title="清零/累加"
                      style="width: 468px"
            />
            <span>
            <q-icon name="iconfont icontubiao-72" class="text-grey" style="margin-left: 5px;margin-top: 10px;font-size: 14px" />
            <q-tooltip max-width="500px">
              <div>例如: 本次采集的计数值为30，上次采集的计数值为500。当选择累加，则认为此段时间的产量为530；当选择清零，则认为此段时间的仍为500</div>
            </q-tooltip>
          </span>
          </div>
          <yz-input
            v-model.trim="form.addr"
            title="点位地址"
            :is-disable="form.serviceTypeId==='DevPower'"
            :rules="addrRules"
          />

          <yz-input v-model="form.dataType"
                    inputType="select"
                    :rules="[0]"
                    :options="dataOptions"
                    title="数据类型(采集)"
                    v-if="form.serviceTypeId!=='DevPower'"
          />
          <yz-input v-model="form.repName"
                    inputType="input"
                    :rules="repNameRules"
                    title="上报名称"
                    :maxlength="15"
                    :hint-rule="[val => val !== null && !/\:+/.test(val) || '上报名称不能包含冒号']"
                    :is-disable="form.repType === '1'|| form.repType === '2'"
          />
          <yz-input v-model="form.repDataType"
                    inputType="select"
                    :rules="[0]"
                    :options="dataTypeReportOption"
                    title="数据类型(上报)"
          />
          <yz-input v-model="form.unit"
                    title="单位"
                    :maxlength="5"
                    v-if="form.repType === '4'"
          />
          <div class="title">点位换算</div>
          <yz-input v-model="form.expression"
                    title="换算公式"
                    :hint-rule="[val => val ? /(?=.*[xX])[+\-*/?()xX0-9\\']/.test(val) || '请输入加号、减号、乘号、除号、问号、左括号、斜杠、单引号、右括号或数字,并且必须含有x' : () => true]"
          >
            <template v-slot:hint>
              注：x代表采集的原始值；换算表达式中的()为英文半角字符
            </template>
          </yz-input>
          <div class="title" v-if="showPointOther">其他</div>
          <yz-input v-model="form.digit"
                    title="小数位数"
                    inputType="select"
                    :options="digitOptions"
                    v-if="showPointOther"
          />
        </div>
      </q-form>
      <q-separator style="width:100%"/>
      <div class="text-center form-inline" style="display:block;padding: 10px 20px">
        <q-btn class="q-mr-md" outline color="primary" :loading="loading" @click="hideDialog">
          <span>取消</span>
        </q-btn>
        <q-btn
          class="q-mr-md"
          label="保存"
          :loading="loading"
          color="primary"
          unelevated
          @click="submit(false)"/>
        <q-btn
          v-if="!isEdit"
          label="保存并继续"
          :loading="loading"
          color="primary"
          unelevated
          @click="submit(true)"/>
      </div>
    </div>
  </basic-dialog>
</template>

<script>
// eslint-disable-next-line import/named
import {
  dataTypeOption,
  reportNameOption,
  reportTypeOption,
  partcountType,
  digitOptions,
  dataTypeReportOption
} from './constant'
import _ from 'lodash'

export default {
  name: 'add-edit-point-dialog',
  props: {
    tableDataAll: {
      type: Array,
      default: () => []
    },
    controllerType: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      partcountType,
      digitOptions,
      addEditDialog: false,
      isEdit: false,
      form: {
        'partcountType': '1',
        'addr': '',
        'repType': '',
        'serviceTypeId': '',
        'repName': '',
        'deviceNum': '',
        'dataType': '',
        'repDataType': '',
        'expression': '',
        'unit': '',
        'digit': ''
      },
      loading: false,
      nameOptions: reportNameOption,
      dataOptions: dataTypeOption,
      dataTypeReportOption: dataTypeReportOption,
      repNameRules: [],
      addrRules: []
    }
  },
  watch: {
    'form.repType': {
      handler: function (val) {
        // 如果为报警或者实时数据，添加必填校验
        if (val === '3' || val === '4') {
          this.repNameRules = [0]
        } else {
          if (this.$refs.form) {
            this.$refs.form.resetValidation()
          }
          this.repNameRules = []
        }
        // 修改关联的serviceTypeId的值
        if (this.nameOptionData.length > 0) {
          this.form.serviceTypeId = this.nameOptionData[0].value
        } else {
          this.form.serviceTypeId = ''
        }
      }
    },
    'form.serviceTypeId': {
      immediate: true,
      handler: function (val) {
        if (val === 'DevPower') {
          this.addrRules = []
          this.form.addr = ''
        } else {
          if (this.$refs.form) {
            this.$refs.form.resetValidation()
          }
          this.addrRules = [0]
        }
      }
    },
    'form.dataType': {
      handler: function (val) {
        if (val && !this.isEdit) {
          const string = ['2', '9']
          const int = ['1', '0', '3', '4', '5', '10', '11']
          const double = ['7', '8']
          if (string.indexOf(val) > -1) {
            this.form.repDataType = 2
          } else if (int.indexOf(val) > -1) {
            this.form.repDataType = 1
          } else if (double.indexOf(val) > -1) {
            this.form.repDataType = 3
          }
        }
      }
    },
    'form.repDataType': {
      handler: function (val) {
        if (val === 3 && !this.form.digit) {
          this.form.digit = 2
        }
      }
    }
  },
  computed: {
    hasDevPower () {
      // 如果是编辑且当前数据是DevPower的话则回显
      if (this.isEdit && this.form.serviceTypeId === 'DevPower') {
        return false
      }
      // 如果选择了设备
      if (this.form.deviceNum) {
        // 筛选该设备
        const currentDeviceData = this.tableDataAll.filter(item => item.deviceNum === this.form.deviceNum)
        // 如果有该设备
        if (currentDeviceData?.length) {
          // 判断该设备是否存在DevPower
          return currentDeviceData.some(item => item.serviceTypeId === 'DevPower')
        }
      }
      return false
    },
    showPointCalc () {
      // 只有实时数据才显示
      return this.form.repType === '4'
    },
    showPointOther () {
      // 只有实时数据才显示
      // 判断上报的数据类型
      if (this.form.repDataType + '' === '3') {
        return true
      }
      return false
    },
    nameOptionData () {
      if (this.isEnergy) {
        // 能耗计数只有A
        if (this.form.repType === '2') {
          return this.nameOptions.filter(item => item.value === 'A')
        }
      } else {
        // 状态显示H、L、DevPower
        // 计数显示H、L、A
        // 报警显示H、L
        if (this.form.repType === '1') {
          return this.nameOptions.filter(item => item.value === 'H' || item.value === 'L')
        } else if (this.form.repType === '2') {
          return this.nameOptions.filter(item => item.value === 'H' || item.value === 'L' || item.value === 'A')
        } else if (this.form.repType === '3') {
          return this.nameOptions.filter(item => item.value === 'H' || item.value === 'L')
        }
      }
      return []
    },
    isEnergy () {
      return this.controllerType + '' === '2'
    },
    typeOptions () {
      if (this.isEnergy) {
        // 能耗只有计数和实时数据
        return reportTypeOption.filter(item => (item.value !== '1' && item.value !== '3'))
      }
      return reportTypeOption
    }
  },
  methods: {
    // 显示弹框
    showDialog (form = {}, type) {
      this.addEditDialog = true
      this.isEdit = type === 'edit'
      if (this.isEdit) {
        this.form = _.cloneDeep(form)
        this.$nextTick(() => {
          this.form.serviceTypeId = form.serviceTypeId
        })
      } else {
        Object.assign(this.form, this.$options.data.call(this).form)
      }
    },
    // 关闭弹框
    hideDialog () {
      this.addEditDialog = false
    },
    // 提交
    submit (isContinue = false) {
      this.$refs.form.validate(true).then(result => {
        if (result) {
          // 构造数据
          const data = {
            ...this.form,
            dataType: this.form.serviceTypeId !== 'DevPower' ? this.form.dataType : '',
            dataTypeName: this.form.serviceTypeId !== 'DevPower' ? this.dataOptions.find(item => item.value === this.form.dataType)?.label : '',
            digit: this.form.repDataType === 3 ? this.form.digit : '',
            repDataTypeName: this.dataTypeReportOption.find(item => item.value === this.form.repDataType)?.label || '',
            reportTypeName: this.form.serviceTypeId ? this.typeOptions.find(item => item.value === this.form.repType)?.label + `(${this.form.serviceTypeId})` : this.typeOptions.find(item => item.value === this.form.repType)?.label
          }
          // 如果是编辑的话
          if (this.isEdit) {
            this.$emit('edit', data)
          } else {
            data.id = Number(new Date()) + Math.random().toString(36).slice(-8)
            this.$emit('add', data)
          }
          // 如果是并继续,恢复初始状态,否则关闭弹框
          if (isContinue) {
            Object.assign(this.form, this.$options.data.call(this).form)
          } else {
            this.addEditDialog = false
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
/deep/ .dialog-content .name{
  width: 116px;
}
.title{
  line-height: 1;
  font-size: 16px;
  font-weight: bold;
  color: #027BE3;
  margin-bottom: 16px;
}
</style>
